<template>
  <div class="order-detail-container">
    <!-- 导航栏 -->
    <div class="navbar">
      <div class="nav-content">
        <div class="logo">
          <span class="logo-icon">✈️</span>
          <span class="logo-text">旅游平台</span>
        </div>
        <div class="nav-user">
          <!-- 通知中心 -->
          <NotificationCenter />
          
          <el-button @click="router.back()" type="text">
            <el-icon><ArrowLeft /></el-icon>
            返回
          </el-button>
        </div>
      </div>
    </div>

    <!-- 页面内容 -->
    <div class="content" v-loading="loading">
      <el-empty v-if="!loading && !order" description="订单不存在" />
      
      <div v-if="order" class="order-detail">
        <!-- 订单状态卡片 -->
        <div class="status-card">
          <div class="status-icon">
            <el-icon v-if="order.status === 'pending'" size="48" color="#e6a23c">
              <Clock />
            </el-icon>
            <el-icon v-else-if="order.status === 'paid'" size="48" color="#67c23a">
              <CircleCheck />
            </el-icon>
            <el-icon v-else-if="order.status === 'completed'" size="48" color="#409eff">
              <Select />
            </el-icon>
            <el-icon v-else size="48" color="#f56c6c">
              <Close />
            </el-icon>
          </div>
          <div class="status-info">
            <h2>{{ getStatusText(order.status) }}</h2>
            <p v-if="order.status === 'pending'">请尽快完成支付</p>
            <p v-else-if="order.status === 'paid'">订单已支付成功</p>
            <p v-else-if="order.status === 'completed'">订单已完成</p>
            <p v-else>订单已取消</p>
          </div>
        </div>

        <!-- 订单信息 -->
        <div class="info-section">
          <h3>订单信息</h3>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="订单号">{{ order.order_no }}</el-descriptions-item>
            <el-descriptions-item label="订单状态">
              <el-tag :type="getStatusType(order.status)">
                {{ getStatusText(order.status) }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="创建时间">{{ formatTime(order.created_at) }}</el-descriptions-item>
            <el-descriptions-item label="支付时间" v-if="order.paid_at">
              {{ formatTime(order.paid_at) }}
            </el-descriptions-item>
            <el-descriptions-item label="更新时间">{{ formatTime(order.updated_at) }}</el-descriptions-item>
          </el-descriptions>
        </div>

        <!-- 景点信息 -->
        <div class="info-section">
          <h3>景点信息</h3>
          <div class="attraction-card">
            <h4>{{ order.attraction_name || '景点名称' }}</h4>
            <el-descriptions :column="2" border>
              <el-descriptions-item label="数量">{{ order.quantity }}张</el-descriptions-item>
              <el-descriptions-item label="单价">¥{{ order.unit_price }}</el-descriptions-item>
              <el-descriptions-item label="总金额" :span="2">
                <span class="total-amount">¥{{ order.total_amount }}</span>
              </el-descriptions-item>
            </el-descriptions>
          </div>
        </div>

        <!-- 联系人信息 -->
        <div class="info-section" v-if="order.contact_name || order.contact_phone">
          <h3>联系人信息</h3>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="联系人姓名">{{ order.contact_name }}</el-descriptions-item>
            <el-descriptions-item label="联系电话">{{ order.contact_phone }}</el-descriptions-item>
          </el-descriptions>
        </div>

        <!-- 备注信息 -->
        <div class="info-section" v-if="order.notes">
          <h3>备注</h3>
          <div class="notes-content">{{ order.notes }}</div>
        </div>

        <!-- 操作按钮 -->
        <div class="action-buttons">
          <el-button @click="router.push('/orders')" type="default">返回订单列表</el-button>
          <el-button
            @click="handleContactMerchant"
            type="success"
            :icon="ChatRound"
          >
            联系商家
          </el-button>
          <el-button
            v-if="order.status === 'pending'"
            @click="payOrder"
            type="primary"
            size="large"
          >
            立即支付 ¥{{ order.total_amount }}
          </el-button>
          <el-button
            v-if="order.status === 'pending'"
            @click="cancelOrder"
            type="danger"
          >
            取消订单
          </el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ArrowLeft, Clock, CircleCheck, Select, Close, ChatRound } from '@element-plus/icons-vue'
import { travelAPI, chatAPI } from '../api/index.js'
import wsClient from '../utils/websocket.js'
import NotificationCenter from '../components/NotificationCenter.vue'

const router = useRouter()
const route = useRoute()

const loading = ref(false)
const order = ref(null)
let paymentPollingTimer = null // 支付状态轮询定时器

// 格式化时间
const formatTime = (time) => {
  if (!time) return ''
  const date = new Date(time)
  return date.toLocaleString('zh-CN')
}

// 获取状态类型
const getStatusType = (status) => {
  const typeMap = {
    'pending': 'warning',
    'paid': 'success',
    'completed': 'info',
    'cancelled': 'danger'
  }
  return typeMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const textMap = {
    'pending': '待支付',
    'paid': '已支付',
    'completed': '已完成',
    'cancelled': '已取消'
  }
  return textMap[status] || status
}

// 加载订单详情
const loadOrderDetail = async () => {
  const orderId = parseInt(route.params.id)
  if (!orderId) {
    ElMessage.error('订单ID无效')
    return
  }

  loading.value = true
  try {
    const response = await travelAPI.getOrderDetail(orderId)
    order.value = response
    
    // 如果订单状态是待支付，启动定时轮询
    if (response.status === 'pending') {
      startPaymentPolling()
    } else {
      stopPaymentPolling()
    }
  } catch (error) {
    console.error('加载订单详情失败:', error)
    ElMessage.error(error.response?.data?.detail || '加载订单详情失败')
  } finally {
    loading.value = false
  }
}

// 同步订单支付状态
const syncPaymentStatus = async () => {
  if (!order.value || order.value.status !== 'pending') {
    return
  }

  try {
    const response = await travelAPI.syncOrderPaymentStatus(order.value.order_no)
    
    if (response.code === 'success' && response.order_status === 'paid') {
      // 支付成功，停止轮询并刷新订单详情
      stopPaymentPolling()
      await loadOrderDetail()
      ElMessage.success('支付成功！订单状态已更新')
    }
  } catch (error) {
    console.error('同步支付状态失败:', error)
    // 不显示错误消息，避免打扰用户
  }
}

// 启动支付状态轮询
const startPaymentPolling = () => {
  // 如果已经有定时器在运行，先清除
  stopPaymentPolling()
  
  // 立即同步一次
  syncPaymentStatus()
  
  // 每5秒轮询一次支付状态
  paymentPollingTimer = setInterval(() => {
    syncPaymentStatus()
  }, 5000)
}

// 停止支付状态轮询
const stopPaymentPolling = () => {
  if (paymentPollingTimer) {
    clearInterval(paymentPollingTimer)
    paymentPollingTimer = null
  }
}

// 支付订单
const payOrder = async () => {
  if (!order.value) return

  try {
    await ElMessageBox.confirm(
      `确认支付订单 ${order.value.order_no}，金额：¥${order.value.total_amount}？`,
      '确认支付',
      {
        confirmButtonText: '确认支付',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    loading.value = true
    // 使用新的支付接口
    const response = await travelAPI.createPayment({
      order_id: order.value.id,
      payment_method: 'alipay'
    })
    
    // 如果返回了支付URL，跳转到支付页面
    if (response.payment_url) {
      ElMessage.success('正在跳转到支付页面...')
      // 在新窗口打开支付页面
      window.open(response.payment_url, '_blank')
      // 或者直接跳转
      // window.location.href = response.payment_url
    } else {
      ElMessage.success('支付创建成功')
    }
    
    // 刷新订单详情
    await loadOrderDetail()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('支付失败:', error)
      ElMessage.error(error.response?.data?.detail || '支付失败，请稍后重试')
    }
  } finally {
    loading.value = false
  }
}

// 联系商家
const handleContactMerchant = async () => {
  if (!order.value || !order.value.id) {
    ElMessage.error('订单信息无效')
    return
  }

  try {
    // 创建或获取商户聊天房间
    const response = await chatAPI.createMerchantRoom({
      order_id: order.value.id
    })
    
    if (response && response.room_id) {
      // 跳转到聊天页面，并传递房间信息
      router.push({
        path: '/chat',
        query: {
          room_id: response.room_id,
          room_type: 'merchant',
          order_id: order.value.id
        }
      })
    } else {
      ElMessage.error('创建聊天房间失败')
    }
  } catch (error) {
    console.error('联系商家失败:', error)
    const errorMsg = error.response?.data?.detail || '联系商家失败，该订单暂无关联商家'
    ElMessage.error(errorMsg)
  }
}

// 取消订单
const cancelOrder = async () => {
  if (!order.value) return

  try {
    await ElMessageBox.confirm(
      `确认取消订单 ${order.value.order_no}？`,
      '确认取消',
      {
        confirmButtonText: '确认取消',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    loading.value = true
    await travelAPI.cancelOrder(order.value.id)
    ElMessage.success('订单已取消')
    await loadOrderDetail()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('取消订单失败:', error)
      ElMessage.error(error.response?.data?.detail || '取消订单失败')
    }
  } finally {
    loading.value = false
  }
}

// WebSocket消息处理
const handleWebSocketMessage = (event) => {
  if (event.type === 'message' && event.data) {
    const notification = event.data
    // 如果是订单相关的通知，刷新订单详情
    if (notification.type === 'order' || notification.type === 'payment') {
      // 检查是否是当前订单
      if (notification.data?.order_id === order.value?.id) {
        ElMessage({
          message: notification.message || notification.title,
          type: notification.priority === 'urgent' ? 'error' : 'success',
          duration: 3000
        })
        // 延迟刷新
        setTimeout(() => {
          loadOrderDetail()
        }, 1000)
      }
    }
  }
}

onMounted(() => {
  loadOrderDetail()
  
  // 连接WebSocket
  const token = localStorage.getItem('token')
  if (token) {
    wsClient.connect(token)
    wsClient.onMessage(handleWebSocketMessage)
  }
})

onUnmounted(() => {
  // 清理定时器
  stopPaymentPolling()
  wsClient.offMessage(handleWebSocketMessage)
})
</script>

<style scoped>
.order-detail-container {
  min-height: 100vh;
  background: #f5f5f5;
}

.navbar {
  background: white;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  position: sticky;
  top: 0;
  z-index: 1000;
}

.nav-content {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 64px;
}

.logo {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 20px;
  font-weight: 600;
  color: #409eff;
}

.logo-icon {
  font-size: 24px;
}

.content {
  max-width: 1200px;
  margin: 0 auto;
  padding: 30px 20px;
}

.order-detail {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.status-card {
  background: white;
  border-radius: 8px;
  padding: 40px;
  display: flex;
  align-items: center;
  gap: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.status-icon {
  display: flex;
  align-items: center;
  justify-content: center;
}

.status-info h2 {
  margin: 0 0 8px 0;
  font-size: 24px;
  color: #333;
}

.status-info p {
  margin: 0;
  color: #666;
  font-size: 16px;
}

.info-section {
  background: white;
  border-radius: 8px;
  padding: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.info-section h3 {
  margin: 0 0 20px 0;
  font-size: 18px;
  color: #333;
  border-bottom: 2px solid #409eff;
  padding-bottom: 8px;
}

.attraction-card {
  margin-top: 16px;
}

.attraction-card h4 {
  margin: 0 0 16px 0;
  font-size: 20px;
  color: #333;
}

.total-amount {
  font-size: 24px;
  font-weight: 600;
  color: #ff6b6b;
}

.notes-content {
  padding: 16px;
  background: #f9f9f9;
  border-radius: 4px;
  color: #666;
  line-height: 1.6;
}

.action-buttons {
  display: flex;
  gap: 12px;
  justify-content: flex-end;
  padding-top: 20px;
}
</style>

